import { ElMessage } from 'element-plus';
import { useArticleApi } from '/@/api/article';
import { arrHasData, deepCopy } from '/@/utils';

const { getArticleCateList, getArticleList, editArticle } = useArticleApi();

export const rules = {
	name: [{ required: true, trigger: 'blur' }],
	score: [{ required: true, trigger: 'blur' }],
};
export const useSearch = () => {
	const page = ref({
		pageSize: 10,
		current: 1,
		total: 0,
	});
	const searchForm = ref({
		name: '',
		startTime: null,
		endTime: null,
	});
	const tableData = ref([]);
	const init = async () => {
		let res = await getArticleList({ ...searchForm.value, ...page.value });
		if (res.code !== 200) return;
		const { data, total } = res.data;
		tableData.value = data;
		page.value.total = total;
	};
	onMounted(init);
	return {
		page,
		searchForm,
		tableData,
		init,
	};
};
export const usePic = (ruleForm) => {
	const isShowPicSelector = ref(false);

	return {
		isShowPicSelector,
		selectPic() {
			isShowPicSelector.value = true;
		},
		getPic(pic) {
			if (!arrHasData(pic)) return;
			ruleForm.value.icon = pic[0].imgUrl;
		},
	};
};
export const useAdd = (init) => {
	const isAdd = ref(false);
	const addDialogVisible = ref(false);
	const itemInfo = ref({});
	return {
		addDialogVisible,
		isAdd,
		itemInfo,
		toAdd() {
			addDialogVisible.value = true;
			isAdd.value = true;
		},
		toEdit(row) {
			addDialogVisible.value = true;
			itemInfo.value = deepCopy(row);
			isAdd.value = false;
		},
		async changeStatus(articleItem) {
			let res = await editArticle(articleItem);
			if (res.code === 200) {
				ElMessage.success('更改状态成功！');
			} else {
				init();
			}
		},
		async changeStatusFoot(articleItem) {
			let res = await editArticle(articleItem);
			if (res.code === 200) {
				ElMessage.success('更改状态成功！');
			} else {
				init();
			}
		},
	};
};
export const useCateFormat = () => {
	const cateList = ref([]);
	async function init() {
		let res = await getArticleCateList({
			current: 1,
			pageSize: 99,
		});
		if (res.code !== 200) return;
		cateList.value = res.data.data;
	}
	onMounted(init);
	return {
		initCateList: init,
		cateList,
		pCateList: computed(() => cateList.value.filter((item) => item.parId === 0 || item.parId === null)),
		cateFormat(catId) {
			const cate = cateList.value.find((item) => item.id === catId) || { name: '' };
			return cate.name;
		},
	};
};
